package com.itheima.reggie.controller;

import com.itheima.reggie.common.BaseTest;
import com.itheima.reggie.common.R;
import com.itheima.reggie.pojo.AddressBook;
import com.itheima.reggie.service.AddressBookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 地址管理
 */
@RestController
@RequestMapping("addressBook")
public class AddressBookController {
    @Autowired
    AddressBookService addressBookService;


    @GetMapping("list")
    public R<List<AddressBook>> list(){
        Long userId = BaseTest.get();
        List<AddressBook> list = addressBookService.lambdaQuery().eq(AddressBook::getUserId, userId).list();
        return R.success(list);
    }
    @PostMapping
    public R<String> add(@RequestBody AddressBook addressBook){
        Long userId = BaseTest.get();
        addressBook.setUserId(userId);
        addressBookService.save(addressBook);
        return R.success("添加成功");
    }
    @GetMapping("{id}")
    public R<AddressBook> show(@PathVariable Long id){
        AddressBook addressBook = addressBookService.lambdaQuery().eq(AddressBook::getId, id).one();
        return R.success(addressBook);
    }
    @PutMapping("default")
    public R<AddressBook> updateStatus(@RequestBody AddressBook addressBook){
        Long userId = BaseTest.get();
        addressBookService.update().set("is_default",0).eq("user_id",userId).update();
        addressBook.setIsDefault(1);
        addressBookService.updateById(addressBook);
        return R.success(addressBook);
    }
    @PutMapping
    public R<String> update(@RequestBody AddressBook addressBook){
        addressBookService.updateById(addressBook);
        return R.success("修改成功");
    }
    @DeleteMapping
    public R<String> delete(Long ids){
        addressBookService.removeById(ids);
        return R.success("删除成功");
    }
    @GetMapping("default")
    public R<AddressBook> edit(){
        Long userId = BaseTest.get();
        AddressBook addressBook = addressBookService.query().eq("user_id", userId).eq("is_default", 1)
                .one();
        return R.success(addressBook);
    }

}
